<template>
  <view class="coupons-container">
    <!-- 优惠券类型切换 -->
    <view class="tab-header">
      <view class="tabs">
        <view 
          v-for="(tab, index) in tabs" 
          :key="index"
          :class="['tab-item', activeTab === tab.value ? 'active' : '']"
          @tap="activeTab = tab.value"
        >
          {{ tab.label }}
        </view>
      </view>
    </view>

    <!-- 优惠券列表 -->
    <view class="coupon-list">
      <view 
        v-for="coupon in filteredCoupons" 
        :key="coupon.id"
        class="coupon-card"
        :class="coupon.status"
      >
        <view class="coupon-left">
          <view class="amount">
            <text class="currency">¥</text>
            <text class="number">{{ coupon.amount }}</text>
          </view>
          <text class="condition">满{{ coupon.minSpend }}可用</text>
        </view>
        
        <view class="coupon-right">
          <view class="coupon-info">
            <text class="title">{{ coupon.title }}</text>
            <text class="desc">{{ coupon.description }}</text>
            <view class="validity">
              <text class="bi bi-calendar3"></text>
              <text>有效期至：{{ coupon.validUntil }}</text>
            </view>
          </view>
          
          <view class="coupon-action">
            <button 
              class="use-btn"
              :class="coupon.status"
              @tap="useCoupon(coupon)"
              :disabled="coupon.status !== 'valid'"
            >
              {{ getCouponButtonText(coupon.status) }}
            </button>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view v-if="!filteredCoupons.length" class="empty-state">
      <text class="bi bi-ticket-perforated"></text>
      <text>暂无优惠券</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useUserStore } from '@/stores/userStore';

// 定义tab数据
const tabs = [
  { label: '可用', value: 'valid' },
  { label: '已使用', value: 'used' },
  { label: '已过期', value: 'expired' }
];

const activeTab = ref('valid');

// 优惠券数据
const userStore = useUserStore();

// 初始化优惠券数据 - 如果用户信息中没有优惠券，创建一个空数组
if (!userStore.userInfo.coupons) {
  userStore.updateUserInfoLocal({ coupons: [] });
}

// 使用ref而不是computed，以便能够正确响应变化
const coupons = ref(userStore.userInfo.coupons || []);

// 如果没有优惠券数据，添加一些示例数据（仅用于演示）
onMounted(() => {
  if (!coupons.value || coupons.value.length === 0) {
    const demoData = [
      {
        id: '001',
        title: '全场满减券',
        amount: 50,
        minSpend: 300,
        description: '全场通用满300元可用',
        validUntil: '2024-12-31',
        status: 'valid'
      },
  
    ];
    
    // 更新本地数据
    userStore.updateUserInfoLocal({ coupons: demoData });
    coupons.value = demoData;
  }
});

// 根据状态筛选优惠券
const filteredCoupons = computed(() => {
  if (!coupons.value || !Array.isArray(coupons.value)) {
    return [];
  }
  
  return coupons.value.filter(coupon => {
    switch (activeTab.value) {
      case 'valid':
        return coupon.status === 'valid';
      case 'used':
        return coupon.status === 'used';
      case 'expired':
        return coupon.status === 'expired';
      default:
        return true;
    }
  });
});

// 获取按钮文本
const getCouponButtonText = (status) => {
  switch (status) {
    case 'valid':
      return '立即使用';
    case 'used':
      return '已使用';
    case 'expired':
      return '已过期';
    default:
      return '使用';
  }
};

// 使用优惠券
const useCoupon = (coupon) => {
  uni.showModal({
    title: '使用优惠券',
    content: `确定要使用"${coupon.title}"吗？`,
    success: (res) => {
      if (res.confirm) {
        // 找到优惠券并标记为已使用
        const index = coupons.value.findIndex(item => item.id === coupon.id);
        if (index !== -1) {
          coupons.value[index].status = 'used';
          
          // 更新本地存储
          userStore.updateUserInfoLocal({ coupons: coupons.value });
          
          // 同步到云端（可选，取决于应用需求）
          syncCouponsToCloud();
          
          activeTab.value = 'used'; // 切换到已使用标签
          
          uni.showToast({
            title: '已成功使用优惠券',
            icon: 'success'
          });
        }
      }
    }
  });
};

// 同步优惠券到云端（调用updateUserInfo云函数）
const syncCouponsToCloud = async () => {
  try {
    if (!userStore.isLoggedIn) {
      console.log('用户未登录，仅更新本地数据');
      return;
    }
    
    const result = await uniCloud.callFunction({
      name: 'updateUserInfo',
      data: {
        body: JSON.stringify({
          account: userStore.userInfo.account,
          coupons: coupons.value
        })
      }
    });
    
    if (result.result && result.result.status === 1) {
      console.log('优惠券数据同步成功');
    } else {
      console.error('优惠券数据同步失败:', result.result?.message);
    }
  } catch (error) {
    console.error('优惠券数据同步异常:', error);
  }
};
</script>

<style lang="scss" scoped>
.coupons-container {
  min-height: 100vh;
  background: #f8f8f8;
  padding: 20rpx;
}

.tab-header {
  background: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
}

.tabs {
  display: flex;
  justify-content: space-around;
}

.tab-item {
  padding: 16rpx 32rpx;
  font-size: 28rpx;
  color: #666;
  position: relative;
  
  &.active {
    color: var(--td-brand-color);
    font-weight: bold;
    
    &::after {
      content: '';
      position: absolute;
      bottom: -4rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 40rpx;
      height: 4rpx;
      background: var(--td-brand-color);
      border-radius: 2rpx;
    }
  }
}

.coupon-card {
  display: flex;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    left: 180rpx;
    top: 0;
    bottom: 0;
    width: 2rpx;
    background: repeating-linear-gradient(
      to bottom,
      #f8f8f8 0,
      #f8f8f8 6rpx,
      transparent 6rpx,
      transparent 12rpx
    );
  }
  
  &.used,
  &.expired {
    opacity: 0.6;
  }
}

.coupon-left {
  width: 180rpx;
  padding: 30rpx;
  background: var(--td-brand-color);
  color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.amount {
  display: flex;
  align-items: baseline;
  margin-bottom: 10rpx;
}

.currency {
  font-size: 32rpx;
}

.number {
  font-size: 64rpx;
  font-weight: bold;
  line-height: 1;
}

.condition {
  font-size: 24rpx;
  opacity: 0.9;
}

.coupon-right {
  flex: 1;
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.coupon-info {
  flex: 1;
  margin-right: 20rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.desc {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 16rpx;
  display: block;
}

.validity {
  font-size: 24rpx;
  color: #999;
  display: flex;
  align-items: center;
  
  .bi {
    margin-right: 8rpx;
  }
}

.use-btn {
  width: 140rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  border-radius: 30rpx;
  font-size: 24rpx;
  background: var(--td-brand-color);
  color: #fff;
  border: none;
  
  &.used,
  &.expired {
    background: #ccc;
  }
}

.empty-state {
  padding: 100rpx 0;
  text-align: center;
  color: #999;
  
  .bi {
    font-size: 80rpx;
    margin-bottom: 20rpx;
    display: block;
  }
}
</style> 